<?php
//require the hmtl functions
require("HTMLFunctions.php");
require("ValidationFunctions.php");
require('ac_db.inc.php');

//set error reporting
error_reporting(E_ERROR | E_WARNING);

//set credentials for database
setcredentials("tr2286","databases8620", "w4111b.cs.columbia.edu/ADB");

//create DB instance
$db = new Db("Proj1", "Part3");

$errorText = "";

//determine if any information was passed to the script
if(count($_POST) == 0){
	generateLoginHTML($errorText, $db);
}
//otherwise some information was passed 
else{
	
	//first validate the information passed
	if(ValidationFunctions::loginUser($_POST['email'], $_POST['password'], $db)){
		
		//close connection
		$db->closeSession();
		echo "<meta http-equiv='refresh' content='0;url=http://localhost/profile.php?email={$_POST['email']}'>";
		exit;
	}
	//otherwise display login and error
	else{
		$errorText = "<h4><font color=\"red\">Invalid Username/Password Combination. <br>Please try again</font></h4>";
		generateLoginHTML($errorText, $db);
	}
}

function generateLoginHTML($errorText, $db){
	
	//call heder functions
	HTMLFunctions::printHTMLHead("Login");
	HTMLFunctions::printTitles("Login", "You are not Logged In!");

	//print potential error message
	echo($errorText);
	
	echo <<<END_HTML
	<!-- place form in table for appearance formatting-->
		<table>
			<form action="login.php" method=POST>
			<tr>
				<!-- username-->
				<td><p>Email:</p></td>
				<td><input type="text" name="email"></td>
			</tr>
			<tr>
				<!-- password-->
				<td><p>Password:</p></td>
				<td><input type="password" name="password"></td>
			</tr>
			<tr>
				<!-- submit button-->
				<td><br /><input type="submit" value="Login"></form></td>
			</tr>
			<tr>
				<!-- new user-->
				<td><p><a href="newUser.php">New User?</a></p></td>
			</tr>		
		</table>
		</div><!--end of content-->
END_HTML;

	HTMLFunctions::printHTMLEnd();
	
}

?>
